<?php
class CategoryModel extends Model {
	public function deleteCate($id){
		if($id){
			$catePath = $this->where(array('id'=>$id))->getField('cate_path');
			return $this->where(array('cate_path'=>array('LIKE', $catePath.'%')))->delete();
		}
		return false;
	}
	
	//返回地区名称
	public function getCateName($id){
		if(!($cates = F($this->name.'_key_value'))){
			$cates = $this->where(array('status'=>1))->getField('id,name');
			F($this->name.'_key_value', $cates);
		}
		
		return $cates[$id];
	}
	
	public function getAllCateTextArray(){
		return $this->order('id DESC')->getField('id,name,is_best');	
	}
	
	public function getAllCate(){
		$cateList = $this->getAll(array('status'=>1), 'row_sort ASC, id ASC');
		foreach($cateList as $key=>$val){
			//处理导航url
			$cateList[$key]['url'] = setCateUrl($this->name,$val);	
		}
		return $cateList;
	}
	
	/**
	* 构造导航或分类的树形结构
	* @param cateList array 分类列表
	* @param activeUrls array 导航需要选中的url列表,或者分类ID
	* @return array
	*/
	public function getCateTree($cateList = array(), $activeUrls = array()){
		if(!$cateList){
			$cateList = $this->getAllCate();
		}
		
		$catePath = ''; //用来选中一系列的导航

		foreach($cateList as $key=>$val){
			if((strtolower('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']) == strtolower($val['url'])) 
				|| in_array(strtolower($val['url']), array_map('strtolower', $activeUrls))
				|| in_array($val['id'], $activeUrls)
				|| substr_count(strtolower('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']), strtolower($val['url'])) > 0
			){
				$catePath = $val['cate_path'];
				break;
			}
		}
		
		$newCateList = array();
		//导航选中的cate path
		$catePath = array_filter(explode(',', $catePath));
		foreach($cateList as $key=>$val){
			if(!empty($catePath) && in_array($val['id'], $catePath)){
				$cateList[$key]['active'] = 1;	
			}
			if($val['pid'] == 0){
				$newCateList[] = $cateList[$key];
				unset($cateList[$key]);
			}	
		}
		
		foreach($newCateList as $k=>$v){
			$newCateList[$k]['tree'] = $this->getCateSonTree($cateList, $v['id']);	
		}
		return $newCateList;
	}
	private function getCateSonTree($cateList, $code){
		  $newCateList = array();
		  foreach($cateList as $key=>$val){
			  if($val['pid'] == $code){
				  $newCateList[$key] = $cateList[$key];
				  unset($cateList[$key]);
				  $newCateList[$key]['tree'] = $this->getCateSonTree($cateList, $val['id']);	
			  }	
		  }
		  
		  return $newCateList;
	}
}